import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, getRefreshToken, getUserKey } from '@/utils/auth' // 验权
import { getTopNavs } from '@/api/navs'
import { matchPath } from '@/utils/index'
// 获取白名单
import whiteList from '@/utils/whiteList'

router.beforeEach((to, from, next) => {
  NProgress.start()
  let serviceTicket = ''
  if (window.location.href.split('?')[1]) {
    serviceTicket = window.location.href.split('?')[1].split('=')[1]
  }
  if (getToken() && getUserKey()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      var isMatched = matchPath(store.getters.allrouter, to.path)
      // 有token 没有用户信息
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          console.log('GetInfo()-res', res)
          console.log(to)
          getTopNavs({ roleId: res.data.roleId }).then(response => {
            console.log('getTopNavs()-res', response)
            store.dispatch('GetTopMenus', response.data)
            store.dispatch('InitSideNavs', 1) // 顶级路由 默认1;  0 是所有的顶级路由
            store.dispatch('InitRouter').then(() => {
              router.addRoutes(store.getters.allrouter)// 动态添加可访问的路由
              console.log('最终添加进得路由', store.getters.allrouter)
              // 判断访问的地址是否在allrouter中
              if (isMatched === true || to.path === '/dashboard') {
                next({ ...to })
              } else {
                next('/')
              }
            })
          }).catch({})
          // next()
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            // 判断访问的地址是否在allrouter中
            if (isMatched === true || to.path === '/dashboard') {
              next()
            } else {
              next('/')
            }
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 白名单的页面直接跳转
    if (whiteList.route.indexOf(to.path) !== -1) {
      next()
    } else {
      // 判断是否有re_fresh_token
      if (getRefreshToken() && getUserKey()) {
        store.dispatch('RefreshToken').then(res => {
          next()
        }).catch(() => {
          next('/login')
          NProgress.done()
        })
        NProgress.done()
      } else {
        if (serviceTicket) {
          // 通过 serviceTicket 登录
          store.dispatch('LoginServiceTicket', serviceTicket).then(() => {
            next('/')
          })
          NProgress.done()
          // 没有serviceTicket  走我们的登录逻辑
        } else {
          next('/login')
          NProgress.done()
        }
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
